package com.ruoyi.quartz.task;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.service.*;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

/**
 * 定时任务调度测试
 *
 * @author admin
 */
@Component("yunyinqianOrderCheckTask")
public class YunYinQianOrderCheckTask {
    @Resource
    private ITOrderInfoService orderService;
    @Resource
    private ITRecipientInfoService userRecipientService;
    @Resource
    private ChargeService chargeService;
    @Resource
    private LoginService loginService;
    private Log logger = Log.get();

    @Autowired
    private ITSmjGoodListService itSmjGoodListService;

    @Autowired
    private ITSmjMachineListService itSmjMachineListService;

    @Autowired
    private ITSmjOrderInfoService itSmjOrderInfoService;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 检查支付超时的订单。状态为待支付并且当前时间已经超过有效时间
     */
    public void checkOrder() throws Exception {
//        logger.info("CXZF订单查询..");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TOrderInfo query = new TOrderInfo();
//        query.setChannelType("alipay");
        query.setChannel("yunyinqian_pay");
        query.setStatus(1);
        String newdateTime = DateUtils.dealDate("10分钟前");
//        String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        query.getParams().put("beginCreateTime", newdateTime);
        List<TOrderInfo> orderInfos = orderService.selectTOrderInfoListByNoAuth(query);
        if(orderInfos.size()==0){
            logger.info("无在途订单，查询过期订单");
            query.setChannel("yunyinqian_pay");
            query.setStatus(3);
            query.getParams().put("beginCreateTime", DateUtils.dealDate("24小时前"));
            query.getParams().put("groupBy", "true");
            orderInfos = orderService.selectTOrderInfoListByNoAuth(query);
            logger.info("无在途订单，查询过期订单数据：{}",orderInfos.size());
        }
        for (TOrderInfo orderInfo : orderInfos) {
            synchronized (this) {
                if (StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
                    continue;
                }
                TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
                String accountJson = userRecipientInfo.getAccountJson();
                JSONObject accountObj = JSONObject.parseObject(accountJson);
                String token = accountObj.getString("ck");
                HashMap<String, String> headerMap = new HashMap();
                headerMap.put("itoken",token);
                headerMap.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36");
                LocalDate now = LocalDate.now();
                String createdStart = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+"+00:00:00";
                String createdEnd = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+"+23:59:59";
                String qryOrderUrl = "https://yhyser.yunhuiyypay.com/api/payOrder?pageNumber=1&pageSize=10&createdStart="+createdStart+"&createdEnd="+createdEnd+"&unionOrderId="+orderInfo.getPay3rdOrderNo()+"&state=2";
                logger.info("查单 请求地址:{}",qryOrderUrl);

                HttpResponse qryOrderRes = HttpUtils.httpFormGet(qryOrderUrl,headerMap,"","云银签查单","");
                logger.info("查单 返回:{}",qryOrderRes);
                JSONObject  qryOrderResObj = JSONObject.parseObject(qryOrderRes.getBody());
                logger.info("qryOrderUrl 返回：{}",qryOrderResObj.toJSONString());
                if(qryOrderResObj.getIntValue("code")==0){

                    JSONObject data = qryOrderResObj.getJSONObject("data");
                    if(data.getIntValue("total")>0){
                        JSONObject record = (JSONObject)data.getJSONArray("records").get(0);
                        BigDecimal payAmount = new BigDecimal(orderInfo.getMoney()).setScale(2);
                        if (record.getString("state").equals("2") && record.getString("mchOrderNo").equals(orderInfo.getPay3rdOrderNo()) && new BigDecimal(record.getString("amount")).compareTo(payAmount) == 0) {

                            MsgPayResult msgPayResult = new MsgPayResult();
                            msgPayResult.setChannel(orderInfo.getChannel());
                            msgPayResult.setTradeNo(orderInfo.getId().toString());
                            msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                            msgPayResult.setOrderId(orderInfo.getPay3rdOrderNo());
                            msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                            msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                            msgPayResult.setChannelPayMsgResult(qryOrderResObj.toJSONString());
                            ResponseData responseData = chargeService.updateOrderPayResult(false, orderInfo.getId(), msgPayResult, false);
                            chargeService.notifyUserPaySucc(orderInfo.getId());
                            logger.info("云银签订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney() + " 处理结果：{}", responseData.getSuccess());
                        }
                    }
                }
            }
        }
    }

}
